package io.ooad.jenkins.shuren;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import retrofit2.Response;

import java.io.IOException;

/**
 * Created by yyang on 2017/1/3.
 */
public class LoginCommand extends BaseCommand {

    private String username;
    private String password;

    public LoginCommand(ShurenyunService service, String username, String password) {
        super(service);
        this.username = username;
        this.password = password;
    }

    @Override
    public Response<JsonNode> execute() {
        ObjectNode loginInfo = getMapper().createObjectNode();
        loginInfo.set("userName", new TextNode(username));
        loginInfo.set("password", new TextNode(password));
        try {
            Response<JsonNode> response = getService().login(loginInfo).execute();
            if (response.isSuccessful()) {
                JsonNode result = response.body();
                AuthHolder.set(result.get("data").asText());
                return response;
            } else {
                throw new RuntimeException("登录失败");
            }
        } catch (IOException e) {
            throw new RuntimeException("无法访问数人云");
        }
    }
}
